import requests
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
import time
from bs4 import BeautifulSoup
# from strategy_backtest.dao import dao_backtest
from settings import backtest_header
from util import cookie_to_str, get_backtest_id, get_data


class MyStrategy:
    """
    传入的browser是在模拟交易的页面，下一步我要处理策略回测的数据。
    我会通过browser进入到我的策略的页面。
    """
    def __init__(self):
        self.data_list = []
        self.header = backtest_header
        self.url = "https://ycjq.95358.com"
        self.backtest_url = "https://ycjq.95358.com/algorithm/backtest/stats?backtestId=%s&ajax=1"

    def next_my_strategy(self, browser):
        wait = WebDriverWait(browser, 5)
        button = browser.find_element_by_link_text("我的策略")
        my_strategy_url = button.get_attribute("href")
        browser.get(my_strategy_url)
        time.sleep(5)
        wait.until(EC.presence_of_all_elements_located((By.TAG_NAME, "tbody")))
        page = browser.page_source
        self.find_page_strategy(page, browser)

    def find_page_strategy(self, page, browser):
        soup = BeautifulSoup(page, "lxml")
        tds = soup.find_all("td", class_="name")
        for td in tds:
            strategy_name = td.find("a").text
            next_url = td.find("a").attrs["href"]
            current_url = self.url + next_url
            # False表示策略回测数据已经存在(不需要再写入数据)，
            # True表示策略的回测的数据不存在(需要写入数据)
            is_insert = dao_backtest.dao_select_strategy_backtest(strategy_name)
            if is_insert:
                self.next_stratetgy_backtest(browser, current_url)
            else:
                continue

    def next_stratetgy_backtest(self, browser, url):
        """
        跳转到回测的页面
        :param browser:
        :return:
        """
        browser.get(url)
        jump = browser.find_element_by_link_text("跳过")
        jump.click()
        button = browser.find_element_by_id("daily-new-backtest-button")
        button.click()
        referer = browser.current_url
        cookies = cookie_to_str(browser.get_cookies())
        self.header["Referer"] = referer
        self.header["Cookie"] = cookies
        self.get_backtest_data(referer)

    def get_backtest_data(self, backtest_url):
        """
        通过requests来请求对应的接口，得到回测的基本数据
        :return:
        """
        data = get_data()
        backtest_id = get_backtest_id(backtest_url)
        url = self.backtest_url % backtest_id
        response = requests.post(url, data=data, headers=self.header)


my_strategy = MyStrategy()

